package com.leyou.page.service;

import com.leyou.common.exception.pojo.ExceptionEnum;
import com.leyou.common.exception.pojo.LyException;
import com.leyou.item.client.ItemClient;
import com.leyou.item.dto.SpecGroupDTO;
import com.leyou.item.dto.SpuDTO;
import com.leyou.item.entity.Brand;
import com.leyou.item.entity.Category;
import com.leyou.item.entity.Sku;
import com.leyou.page.entity.Comment;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import org.thymeleaf.context.Context;
import org.thymeleaf.spring5.SpringTemplateEngine;

import java.io.File;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class PageService {

    @Autowired
    private ItemClient itemClient;

    @Value("${ly.static.itemDir}")
    private String itemDir;

    @Value("${ly.static.itemTemplate}")
    private String itemTemplate;
    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private SpringTemplateEngine templateEngine;

    public Map<String, Object> itemInfo(Long id) {
        //根据spuId查询SpuDTO  包含sku集合spuDetail
        SpuDTO spuDTO = itemClient.findSpuDTOById(id);
        //根据三个分类id的集合查询三个分类对象的集合
        List<Category> categories = itemClient.findCategoriesByIds(spuDTO.getCategoryIds());
        //根据品牌id查询品牌对象
        Brand brand = itemClient.findBrandById(spuDTO.getBrandId());
        //根据分类id查询规格组集合 及其规格组下规格参数集合
        List<SpecGroupDTO> specGroupDTOS = itemClient.findGroupWithParams(spuDTO.getCid3());
        //获取skus集合
        List<Sku> skus = spuDTO.getSkus();
        //遍历集合，把库存为0的sku去掉
        for (int i = skus.size()-1; i >=0 ; i--) {
            if (skus.get(i).getStock()<=0){
                skus.remove(i);
            }
        }

        Map<String, Object> itemInfo = new HashMap<>();
        itemInfo.put("categories", categories);
        itemInfo.put("brand", brand);
        itemInfo.put("spuName", spuDTO.getName());
        itemInfo.put("subTitle", spuDTO.getSubTitle());
        itemInfo.put("detail", spuDTO.getSpuDetail());
        itemInfo.put("skus", spuDTO.getSkus());
        itemInfo.put("specs", specGroupDTOS);
        Query query=new Query(Criteria.where("spuId").is(id.toString()));
        List<Comment> comments = mongoTemplate.find(query, Comment.class);
        itemInfo.put("comments",comments);
        return itemInfo;
    }

    /**
     * 制作静态化页面
     */
    public void createStaticPage(Long id){
        //准备静态化页面的上下文
        Map<String, Object> itemInfo = itemInfo(id);
        Context context = new Context();
        context.setVariables(itemInfo);

        //准备静态页页面要输出的文件对象
        File itemFile = new File(new File(itemDir), id+".html");

        //提供打印流
        try(PrintWriter write = new PrintWriter(itemFile)){
            //制作静态页面
            templateEngine.process(itemTemplate, context, write);
        }catch (Exception e){
            throw new LyException(ExceptionEnum.FILE_WRITER_ERROR);
        }

    }

    public void addPage(Long id) {
        createStaticPage(id);
    }

    public void delPage(Long id) {
        //准备静态页页面要输出的文件对象
        File itemFile = new File(new File(itemDir), id+".html");
        if(itemFile.exists()){
            itemFile.delete();
        }
    }

}
